//
//  MainViewController.swift
//  知乎日报Demo
//
//  Created by Ann on 2017/10/14.
//  Copyright © 2017年 Ann. All rights reserved.
//
//
enum ChoiceDate{
    case lastDate
    case nextData
}

let NewsCellID = "NewsCellID"
let mainImageHeight:CGFloat = 300
let newsRowHeight:CGFloat = 100
let autoInsets:CGFloat = 64

//限制下拉临界点
let criticalPoint:CGFloat = mainImageHeight + 100
import SnapKit
import UIKit

class MainViewController: UIViewController {
    
    //Step.1 界面搭建
    //1. 懒加载控件
    //1.1.1 TableView
    lazy var mainTableView:UITableView = {
    let tbv = UITableView()
       tbv.backgroundColor = UIColor.clear
    return tbv
    }()
    //1.1.2 装载ScrollView的View
    var headerView:HeaderView?
    
    let navView:NavView = {
    let nav = NavView()
        return nav
    }()
    var isCanRefresh:Bool = false
    //同一对象
    var newsViewModel = NewsViewModel()
    
    var news:[StatusList]?{
        didSet{
            mainTableView.reloadData()
            activityView.stopAnimating()
            navView.isStartAnimate = false
            
        }
    }
    
    var currentIndexPath:IndexPath?
    
    lazy var activityView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    
    override func viewDidLoad() {
        super.viewDidLoad()
 
        view.backgroundColor = UIColor.lightGray
        //1.2 去除因为添加导航控制器而产生的自动64点Inset
        //MARK:- 导航控制器属性设置
        self.automaticallyAdjustsScrollViewInsets = false
        self.navigationController?.navigationBar.isHidden = true
       
       
        setMainTableView()
       
        setnavView()
        newsViewModel.refreshTodayNews { (isTrue) in
            if isTrue {
           self.news = self.newsViewModel.news
           self.headerView = HeaderView(topNewsArray: self.newsViewModel.todayNews?.topNews)
           self.setHeaderView()
                //加载完今天的后，需要额外加载多前两天为了给顶部热度新闻匹配
                self.newsViewModel.getYesterdayNews { (isSuccess) in
                    if isSuccess {
                        //self.news = self.newsViewModel.news
                        self.newsViewModel.getYesterdayNews { (isSuccess) in
                            if isSuccess {
                                //self.news = self.newsViewModel.news
                                
                            }
                        }
                    }
                }
                //   ---  end   ---
              }
        }
        
        mainTableView.tableFooterView = activityView
      }


}
extension MainViewController{

    func setHeaderView(){
     
        mainTableView.addSubview(headerView!)
        headerView?.frame = CGRect(x: 0, y: -mainImageHeight, width: ScreenWidth, height: mainImageHeight)
        headerView?.headerViewDelegate = self as! HeaderViewDelegate
    }
    func setMainTableView(){
        //4.1 注册Cell
        mainTableView.register(NewsTableViewCell.self, forCellReuseIdentifier: NewsCellID)
        mainTableView.contentInset = UIEdgeInsetsMake(mainImageHeight, 0, 0, 0)
        mainTableView.rowHeight = newsRowHeight
        mainTableView.delegate = self
        mainTableView.dataSource = self
        mainTableView.showsVerticalScrollIndicator = false
        
        view.addSubview(mainTableView)
      
        
        
        mainTableView.snp.makeConstraints { (make) in
            make.top.equalTo(self.topLayoutGuide.snp.top)
            make.left.equalTo(self.view.snp.left)
            make.right.equalTo(self.view.snp.right)
            make.bottom.equalTo(self.view.snp.bottom)
        }
    }

    func setnavView(){
    self.view.addSubview(navView)
    navView.backgroundColor = UIColor.zh_blueAndAlpha(double: 1)
    navView.snp.makeConstraints { (make) in
        make.left.equalTo(view.snp.left)
        make.top.equalTo(topLayoutGuide.snp.top)
        make.right.equalTo(view.snp.right)
        make.height.equalTo(autoInsets)
        }
    }
}
//MARK:- TableView代理
extension MainViewController:UITableViewDelegate,UITableViewDataSource{

    //MARK: --------------TableView数据源 ------------------
      func numberOfSections(in tableView: UITableView) -> Int {
        
        return news?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return news?[section].news?.count ?? 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NewsCellID, for: indexPath) as! NewsTableViewCell
        
        
        
        if indexPath.section == (news?.count ?? 1) - 1{
            if indexPath.row == (news?[indexPath.section].news?.count ?? 1) - 1{
                 //4.2 当显示到最后一个Cell的时候自动刷新事件
            self.canRefreshMore()
                activityView.startAnimating()
              
                
            }
        }
        let section = indexPath.section
        let NewsList = news?[section]
        
        let last = NewsList?.news?[indexPath.row]
        cell.news  = last
 
        
        return cell
 
        
    }
    //TableView数据源->end
 
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //ALPHA值更变//上拉
        if scrollView.contentOffset.y >= -mainImageHeight && scrollView.contentOffset.y <= -navView.frame.height{
        let temp = -(scrollView.contentOffset.y+navView.frame.height)/(mainImageHeight - navView.frame.height)
        let aph = 1 - temp
        navView.backgroundColor = UIColor.zh_blueAndAlpha(double:aph )
           
        }
 
        
        //下拉刷新判断
        if scrollView.contentOffset.y <= -mainImageHeight-50 && !isCanRefresh{
        isCanRefresh = true
        //print("true")

        } else if scrollView.contentOffset.y >= -mainImageHeight-50 && isCanRefresh {

        isCanRefresh = false
     
        }
        
        //传递下拉进度phase
        if scrollView.contentOffset.y <= -mainImageHeight &&  scrollView.contentOffset.y >= -mainImageHeight-50 {
        
            
            let off = mainImageHeight+50 + scrollView.contentOffset.y
          
            navView.phase = off
        }
        //限制下拉判断
        if scrollView.contentOffset.y < -criticalPoint{
        scrollView.contentOffset = CGPoint(x: 0, y: -criticalPoint)
     
        }
     
            
     
       

        
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        if isCanRefresh {
      navView.isStartAnimate = true
        canRefreshMore()
           
        }
    }
 
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
            currentIndexPath = indexPath
            let newsSection = newsViewModel.news[indexPath.section]
            let news = newsSection.news?[indexPath.row]
            let id = news?.id
            guard id != nil else {
                return
            }
         let detialViewController = NewsDetailViewController(newId: id!)
            detialViewController.detialViewDelegate = self as? NewsDetialViewDelegate
            self.navigationController?.pushViewController(detialViewController, animated: true)
        }
    
    
}
extension MainViewController:NewsDetialViewDelegate,HeaderViewDelegate{
    
    //MARK:------ NewsDetialView代理 ------
    
    func loadAntherDateNews(date: ChoiceDate) {
        if currentIndexPath?.section == 0, currentIndexPath?.row == 0 && date == ChoiceDate.lastDate {
            print("已经是没有更多新新闻了")
            return
        }
        //跳转
               let news_id = date == ChoiceDate.lastDate ? getNextOrLastNewsIdAndChangeCurrentindexPath(indexPath: &currentIndexPath!, choice: ChoiceDate.lastDate) : getNextOrLastNewsIdAndChangeCurrentindexPath(indexPath: &currentIndexPath!, choice: ChoiceDate.nextData)
        
     let  detialViewController = NewsDetailViewController(newId: news_id!)   // NewsDetialViewController()
        
   
        detialViewController.detialViewDelegate = self as NewsDetialViewDelegate
        
        self.navigationController?.pushViewController(detialViewController, animated: true)
        
    }
    
 
    
    
   //MARK:------ HeaderView代理 ------
    
    func showDetialView(indexOf: Int) {
 
        var equalStatus:Status?
        //通过ID获取同一新闻对象
          let id = newsViewModel.todayNews!.topNews![indexOf].id
        for i in 0 ..< newsViewModel.news.count {
            for item in newsViewModel.news[i].news! {
                if id == item.id {
                 equalStatus = item
                }
            }
      }
        guard let status = equalStatus else {
            print("找不到当前新闻!")
            return
        }
        var currentSection:Int = 0
        var currentSectionIndext:Int = 0
        
    //2.通过元素获取NewsList所在的的下标
    
        for i in 0...newsViewModel.news.count-1 {
            //如果当前Section存在指定元素则进去查找其其下标
            if newsViewModel.news[i].news!.contains(status){
             currentSection = i
             currentSectionIndext = (newsViewModel.news[i].news?.index(of: status))!
                
            }
     }
        //最后将当前indexPath上传
        
        currentIndexPath = IndexPath(row: currentSectionIndext, section: currentSection)
        
        //跳转
       
        let newsSection = newsViewModel.news[currentIndexPath!.section]
        let news = newsSection.news?[currentIndexPath!.row]
        let _id = news!.id
        guard _id != nil else {
            return
        }
        let detialViewController = NewsDetailViewController(newId: _id)
        detialViewController.detialViewDelegate = self as? NewsDetialViewDelegate
        self.navigationController?.pushViewController(detialViewController, animated: true)
   
  }


    func canRefreshMore(){
        
        newsViewModel.getYesterdayNews { (isSuccess) in
            if isSuccess {
                self.news = self.newsViewModel.news
                
            }
        }

    
    }
    
  
   
    func getNextOrLastNewsIdAndChangeCurrentindexPath( indexPath: inout IndexPath,choice:ChoiceDate)->Int?{
        
        let currentSection = newsViewModel.news[ indexPath.section]
        //超出今天的新闻数量
        if choice == ChoiceDate.nextData{
            
            if (indexPath.row+1) == currentSection.news?.count {
                
                let nextSection = newsViewModel.news[indexPath.section+1]
                
                //获取id同时修改当前indexPath1
                indexPath = IndexPath(row: 0, section: indexPath.section+1)
                
                return  nextSection.news?[0].id
            }
            let news = currentSection.news?[indexPath.row + 1]
            
            //获取id同时修改当前indexPath2
            indexPath = IndexPath(row: indexPath.row + 1, section: indexPath.section)
            return news?.id
            
        }
        //---------------------
        
        if indexPath.row == 0 {
            
            let lastSection = newsViewModel.news[indexPath.section-1]
            //获取id同时修改当前indexPath3
            indexPath = IndexPath(row: indexPath.row, section: indexPath.section-1)
            return lastSection.news?.last?.id
            
        }
        let news = currentSection.news?[indexPath.row - 1]
        //获取id同时修改当前indexPath4
        indexPath = IndexPath(row: indexPath.row-1, section: indexPath.section)
        return  news?.id
    }
    
    
}
